import { createRouter, createWebHashHistory } from 'vue-router';
import Home from '@/pages/home/Home.vue';
import Login from '@/pages/login/Login.vue';
import Tools from '@/pages/tools/Tools.vue';
import NotFound from '@/pages/404/NotFound.vue';
import Config from '@/pages/config/Config.vue';

// 定义路由
const routes = [
    { path: '/', redirect: '/home' },
    { path: '/home', component: Home },
    { path: '/login', component: Login, meta: { hideHeaderFooter: true } },
    { path: '/tools', component: Tools },
    { path: '/config', component: Config, meta: { requiresAuth: true } },
    { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }, // 捕获所有未匹配路径
];

// 创建路由实例
const router = createRouter({
    history: createWebHashHistory(),
    routes,
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
    const isAuthenticated = !!localStorage.getItem('token'); // 检查本地存储中是否有 token

    if (to.matched.some((record) => record.meta.requiresAuth) && !isAuthenticated) {
        // 如果路由需要身份验证且用户未登录，则重定向到登录页，并携带回调链接
        next({
            path: '/login',
            query: { cb_url: to.fullPath },
        });
    } else if (to.path === '/login' && isAuthenticated) {
        // 如果用户已登录且试图访问登录页，则重定向到首页
        next('/home');
    } else {
        // 其他情况正常跳转
        next();
    }
});

export default router;
